// Cornerstone 图像加载器
import { imageLoader } from '@cornerstonejs/core';

/**
 * DICOM图像加载器
 */
export const dicomImageLoader = imageLoader.loadImage;

/**
 * Web图像加载器
 * @param {string} imageId - 图像ID
 * @returns {Promise} 图像加载Promise
 */
export function webImageLoader(imageId) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    
    image.onload = function() {
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      
      canvas.width = image.width;
      canvas.height = image.height;
      context.drawImage(image, 0, 0);
      
      const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
      const pixelData = new Uint8Array(imageData.data.length);
      
      // 转换为灰度
      for (let i = 0; i < imageData.data.length; i += 4) {
        const gray = Math.round(
          0.299 * imageData.data[i] +
          0.587 * imageData.data[i + 1] +
          0.114 * imageData.data[i + 2]
        );
        pixelData[i / 4] = gray;
      }
      
      const cornerstoneImage = {
        imageId: imageId,
        minPixelValue: 0,
        maxPixelValue: 255,
        slope: 1,
        intercept: 0,
        windowCenter: 127,
        windowWidth: 255,
        render: undefined,
        getPixelData: () => pixelData,
        rows: canvas.height,
        columns: canvas.width,
        height: canvas.height,
        width: canvas.width,
        color: false,
        columnPixelSpacing: 1,
        rowPixelSpacing: 1,
        invert: false,
        sizeInBytes: pixelData.length
      };
      
      resolve(cornerstoneImage);
    };
    
    image.onerror = function(error) {
      reject(new Error(`Failed to load image: ${imageId}`));
    };
    
    // 移除协议前缀
    const url = imageId.replace('web:', '');
    image.src = url;
  });
}